using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lavka.Core;
using Lavka.Models;

namespace Lavka.Controllers
{
    [Authorize(Roles = "Administrators")]
    public class CategoriesController : Controller
    {
        public List<Parameters> CurrentParameters
        {
            get { return (List<Parameters>)Session["Parameters"]; }
            set { Session["Parameters"] = value; }
        }

        public List<Articles> CurrentArticles
        {
            get
            {
                if (Session["CategoryArticles"] == null) Session["CategoryArticles"] = new List<Articles>();
                return (List<Articles>)Session["CategoryArticles"];
            }
            set { Session["CategoryArticles"] = value; }
        }

        private LavkaDbEntities context = new LavkaDbEntities();

        // GET: /Categories/
        public ViewResult Index()
        {
            var root = context.Caterories.Where(c => c.ParentId == null);
            return View(context.Caterories.Include("Products").ToList().Except(root));
        }

        //
        // GET: /Categories/Details/5

        public ViewResult Details(int id)
        {
            Caterories caterories = context.Caterories.Single(x => x.CategoryId == id);
            return View(caterories);
        }

        //
        // GET: /Categories/Create

        public ActionResult Create()
        {
            ViewData["ParentCategories"] = new SelectList(context.Caterories.ToList(), "CategoryId", "Name");
            CurrentParameters = new List<Parameters>();
            CurrentArticles = new List<Articles>();
            return View();
        } 

        //
        // POST: /Categories/Create

        [HttpPost]
        public ActionResult Create(Caterories caterories, HttpPostedFileBase file)
        {
            caterories.ParentId = Convert.ToInt32(Request.Form["ddlParentCategories"]);
            if (ModelState.IsValid)
            {
                context.Caterories.AddObject(caterories);
                context.SaveChanges();
                caterories.Photo = FileHelper.UploadPhoto(file, "categories",caterories.CategoryId);
                context.SaveChanges();
                UpdateParameters(caterories.CategoryId, true);
                UpdateArticles(caterories);

                return RedirectToAction("Index");  
            }

            return View(caterories);
        }
        
        //
        // GET: /Categories/Edit/5
 
        public ActionResult Edit(int id)
        {
            var current = context.Caterories.Where(x => x.CategoryId == id);
            Caterories caterories = context.Caterories.Single(x => x.CategoryId == id);
            ViewData["ParentCategories"] = new SelectList(context.Caterories.Except(current).ToList(), "CategoryId", "Name", caterories.ParentId);

            CurrentParameters = ParametersHelper.GetParametersByCategoryId(id);
            CurrentArticles = CategoriesHelper.GetCategoryArticles(id, context);

            return View(caterories);
        }

        //
        // POST: /Categories/Edit/5
        [HttpPost]
        public ActionResult Edit(Caterories caterories, HttpPostedFileBase file)
        {

            caterories.ParentId = Convert.ToInt32(Request.Form["ddlParentCategories"]);

            caterories.Photo = FileHelper.UploadPhoto(file, "categories", caterories.CategoryId);

            if (ModelState.IsValid)
            {              
                context.Caterories.Attach(caterories);
                context.ObjectStateManager.ChangeObjectState(caterories, EntityState.Modified);

                context.SaveChanges();

                UpdateArticles(caterories);

                UpdateParameters(caterories.CategoryId, true);

                return RedirectToAction("Index");
            }
            return View(caterories);
        }


        //
        // GET: /Categories/Delete/5
        public ActionResult Delete(int id)
        {
            Caterories caterories = context.Caterories.Single(x => x.CategoryId == id);
            return View(caterories);
        }

        // GET
        public ActionResult AddArticle()
        {
            return PartialView("AddArticle");
        }

        // POST
        [HttpPost]
        public ActionResult AddArticle(int articleId)
        {
            var article = context.Articles.Where(a => a.ArticleId == articleId).FirstOrDefault();
            CurrentArticles.Add(article);
            return PartialView("ArticlesList", CurrentArticles);
        }

        public ActionResult DeleteArticle(int articleId)
        {
            Articles art = CurrentArticles.Where(p => p.ArticleId == articleId).SingleOrDefault();
            CurrentArticles.Remove(art);

            return PartialView("ArticlesList", CurrentArticles);
        }

        // GET
        public ActionResult AddParameter()
        {
            return PartialView("AddParameter");
        }
        //
        // POST: /Categories/Delete/5
        [HttpPost]
        public ActionResult AddParameter(string itemValue)
        {
            Parameters parameter = new Parameters();
            parameter.ParamenterName = itemValue;
            Random random = new Random();
            parameter.ParamenterId = random.Next(-2000, -1000);
            CurrentParameters.Add(parameter);
            return PartialView("ParametersList", CurrentParameters);
        }

        public void UpdateArticles(Caterories caterories)
        {
            caterories.Articles.Clear();
            foreach (Articles art in CurrentArticles)
            {
                caterories.Articles.Add(new Articles()
                {
                    ArticleId = art.ArticleId,
                    Title = art.Title,
                    Body = art.Body,
                    Photo = art.Photo
                });
            }
            context.SaveChanges();
        }

        public void UpdateParameters(int categoryGroupId, bool deleteFromContext)
        {
            if (deleteFromContext)
            {
                foreach (Parameters p in context.Parameters.Where(pr => pr.CategoryId == categoryGroupId))
                {
                    if (p.ParamenterId > 0)
                    {
                        context.Parameters.DeleteObject(p);
                    }
                }
                context.SaveChanges();
            }
            foreach (Parameters p in CurrentParameters)
            {
                Parameters dbParam = new Parameters()
                {
                    ParamenterName = p.ParamenterName,
                    CategoryId = categoryGroupId
                };
                context.Parameters.AddObject(dbParam);
            }
            context.SaveChanges();
        }

        public ActionResult DeleteParameter(int id)
        {
            Parameters prm = CurrentParameters.Where(p => p.ParamenterId == id).SingleOrDefault();
            CurrentParameters.Remove(prm);

            return PartialView("ParametersList", CurrentParameters);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Caterories caterories = context.Caterories.Single(x => x.CategoryId == id);

            CurrentParameters = new List<Parameters>();
            UpdateParameters(id, true);

            context.Caterories.DeleteObject(caterories);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}